const serve = require('./request')
const apiUtils = require('./api-util')

function request(config = {
  method: 'GET',
  url: '',
  headers: [{}],
  params: [{}],
  proxyEnable: false,
  withCredentials: false,
}) {
  let method = config.method || 'GET'
  method = method.toLowerCase()
  const url = config.url || ''
  const headers = config.headers || [{}]
  const params = config.params || [{}]
  const proxyEnable = config.proxyEnable || false
  const withCredentials = config.withCredentials || false

  const lastHeaders = _configParam(headers) || {}
  const lastParams = _configParam(params) || {}
  // console.log('lastParams=', lastParams)

  const proxy = _getProxy(proxyEnable)

  // http://www.axios-js.com/zh-cn/docs/
  return serve({
    url,
    method,
    headers: lastHeaders,
    params: lastParams,
    proxy,
    withCredentials, // send cookies when cross-domain requests
  })
}

function _configParam(params) {
  const lastHeader = {}
  for (let i = 0; i < params.length; i++) {
    const p = params[i] || {}
    const name = p.name
    let value = p.value
    const type = p.type || 'string'
    if (!name) {
      continue
    } else if (!value) {
      switch (type) {
        case 'string':
          value = ''
          break;
        case 'int', 'float':
          value = 0
          break;
        default:
          value = null
          break;
      }
    } else if (value) {
      if (type !== 'string') {
        if (type === 'int') {
          value = parseInt(value)
        } else if (type === 'float') {
          value = parseFloat(value)
        } else {
          value = JSON.parse(value)
        }

        if (value === NaN) {
          value = 0
        }
      }
    }
   lastHeader[name] = value
  }
  return lastHeader
}

function _getProxy(enable) {
  if (!enable) return;

  let proxy = {}
  if (SW_NODE_ENV === 'product') {
    proxy = apiUtils.prod.proxy
  } else {
    proxy = apiUtils.dev.proxy
  }

  const host = proxy.host
  if (!host) return {}
  return proxy
}

export default request